
package com.musiklegal;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.security.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.Toast;
import android.app.Dialog;


import android.content.Context;

import android.content.SharedPreferences;

import android.telephony.TelephonyManager;

import android.widget.EditText;


public class MusikLegal extends Activity 
{
	 public static boolean on = false;
	 public static List<SongD> listDownload=new ArrayList<SongD>();
	 public static List<SongD> myPlaylist=new ArrayList<SongD>();
	 public static TreeSet<SongD> dataSet = new TreeSet<SongD>(new Comparator<SongD>(){
		public int compare(SongD object1, SongD object2) {
			
			return object1.idRing.compareToIgnoreCase(object2.idRing);
		}});
	 //public static ImageLoader imageLoader = new ImageLoader();
     public static SharedPreferences mPreferences;
     ProgressDialog dialog;
     public final static String mainFolder = "/sdcard/.MusikLegal/";
  	 public final static String settingFolder = "/sdcard/.MusikLegal/Setting/";
 	 public final static String listD = "/sdcard/.MusikLegal/Setting/listDownload";
 	 public final static String playlist = "/sdcard/.MusikLegal/Setting/playList";
 	 public final static String albumArtFolder="/sdcard/.MusikLegal/albumArt/";
 	 public final static String cacheFolder = "/sdcard/.MusikLegal/cache/";
 	 public final static String licenceFile ="/sdcard/systemml.sys";
     public static String user;
     static String current_date;
     static String end_subscription;
     static DataHelper db;
     String temp;
     public static PlaylistSender log;
     public static String fbName=null;
     public static String twName=null;
     Handler h;
     public void onResume()
     {
    	 super.onResume();
    	 new Thread(new Runnable(){

			public void run() {
				// TODO Auto-generated method stub
				if(!MusikLegal.internet(getApplicationContext()))
		    	 {
					h.post(new Runnable(){

						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
						}});
		    		 
		    		 //finish();
		    	 }
		    	 else
		    	 {
		    		 if(log.listSong.size()>0)
		         	{
		         		try {
		 					log.send();
		 				} catch (IllegalStateException e) {
		 					// TODO Auto-generated catch block
		 					e.printStackTrace();
		 				} catch (IOException e) {
		 					// TODO Auto-generated catch block
		 					e.printStackTrace();
		 				} catch (SAXException e) {
		 					// TODO Auto-generated catch block
		 					e.printStackTrace();
		 				} catch (ParserConfigurationException e) {
		 					// TODO Auto-generated catch block
		 					e.printStackTrace();
		 				}
		         	}
		    	 }
		    	 
		     
			}});
     }
     
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        //checkingData();
       
        setContentView(R.layout.main);
        h = new Handler();
        Button btn = (Button) this.findViewById(R.id.login);
        Button register = (Button) this.findViewById(R.id.register);
        Button forpass = (Button) findViewById(R.id.forpass);
        Button fbLogin = (Button) findViewById(R.id.fb);
        Button twLogin = (Button) findViewById(R.id.twt);
        final EditText text_box = (EditText) findViewById(R.id.username); 
        text_box.setOnFocusChangeListener(new OnFocusChangeListener() 
        {
        	public void onFocusChange(View v, boolean hasFocus) 
        	{ if (hasFocus==true) 
        	{ if (text_box.getText().toString().compareTo("username")==0) 
        	{ text_box.setText(""); } } } });
        
        final EditText text_box2 = (EditText) findViewById(R.id.password); 
        text_box2.setOnFocusChangeListener(new OnFocusChangeListener() 
        {
        	public void onFocusChange(View v, boolean hasFocus) 
        	{ if (hasFocus==true) 
        	{ if (text_box2.getText().toString().compareTo("password")==0) 
        	{ text_box2.setText(""); } } } });
        
        
        	
		 
		
              btn.setOnClickListener(new OnClickListener() 
              {
                    public void onClick(View v) 
                    {
                    	showDialog(0);
                    	new Thread(new Runnable(){

							public void run() {
								if(MusikLegal.internet(getApplicationContext()))
	                    		{
	                    		 
	                    		//new Thread(new Runnable()
	                    		//{
	    							//public void run() {
	    								//h.post(new Runnable()
	    								//{
	    							//		public void run() {
	    										tryLogin();
	    								//	}});
	    								
	    							//}}).start();
	                    		}
	                    	else
	                    		{
	                    			h.post(new Runnable(){

										public void run() {
											removeDialog(0);
											Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
											
										}});
	                    			
	                    			//finish();
	                    		}
								
							}}).start();
                    	
                    }
              });
              
              fbLogin.setOnClickListener(new OnClickListener(){

				public void onClick(View arg0) {
					if(MusikLegal.internet(getApplicationContext()))
					{
						LoginWeb.p = MusikLegal.this;
						LoginWeb.fromSettings=false;
						LoginWeb.urlTo="http://www.musiklegal.com/fbauth.php?source=mobile&touch=1";
						startActivity(new Intent(getApplicationContext(),LoginWeb.class));
					}
					else
        				{
							Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
							//finish();
        				}
				}});
              twLogin.setOnClickListener(new OnClickListener(){

  				public void onClick(View arg0) {
  					if(MusikLegal.internet(getApplicationContext()))
  					{
  						LoginWeb.p = MusikLegal.this;
  						LoginWeb.urlTo="http://www.musiklegal.com/twauth.php";
  						LoginWeb.fromSettings=false;
  						startActivity(new Intent(getApplicationContext(),LoginWeb.class));
  					}
  					else
      				{
						Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
						//finish();
      				}		
  				}});
        
       
        
        	register.setOnClickListener(new OnClickListener() {
        		public void onClick(View arg0) {
        			if(MusikLegal.internet(getApplicationContext()))
        				startActivity(new Intent(getApplicationContext(), RegisterMenu.class));
        			else
        				Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
			
			}
		});
        	forpass.setOnClickListener(new OnClickListener() {
        		public void onClick(View arg0) {
        			if(MusikLegal.internet(getApplicationContext()))
        				forpass();
        			else
        				Toast.makeText(getApplicationContext(), Settings.gakonek, Toast.LENGTH_SHORT).show();
			
			}
		});
       
}
       
    
    
    protected Dialog onCreateDialog(int id) {
        switch (id) {
              case 0: {
                    dialog = new ProgressDialog(this);
                    dialog.setMessage("Redirecting...");
                    dialog.setIndeterminate(true);
                    dialog.setCancelable(true);
                    return dialog;                   
              }
        }
        return null;
  }
    
   static void checkSubscription(Context c) throws ClientProtocolException, IOException, ParserConfigurationException, SAXException
    {
    	
	    	DefaultHttpClient client = new DefaultHttpClient();
	    	HttpPost subs = new HttpPost("http://secure.musiklegal.com/subscription/check");
	    	 List< BasicNameValuePair > nvss = new ArrayList< BasicNameValuePair >();
	    	 nvss.add(new BasicNameValuePair("USERNAME", mPreferences.getString("UserName", null)));
	    	 nvss.add(new BasicNameValuePair("UID",getUID(c)));
	    	 UrlEncodedFormEntity s_entity = new UrlEncodedFormEntity(nvss,HTTP.UTF_8);
	    	 
	    	 subs.setEntity(s_entity);
	    	 HttpResponse response3 = client.execute(subs);
	    	 HttpEntity responseEntity3 = response3.getEntity();
	    	 SAXParserFactory bpf = SAXParserFactory.newInstance();
	         SAXParser bp = bpf.newSAXParser();
	         XMLReader br = bp.getXMLReader();
	         LoginHandler subsHand = new LoginHandler();
	         br.setContentHandler(subsHand);
	    	 br.parse(retrieveInputStream(responseEntity3));
	    	 ParsedLoginDataSet subset = subsHand.getParsedLoginData();
	    	 //Toast.makeText(getApplicationContext(), mPreferences.getString("UserName", "tes")+ " "+ getUID(this)+subset.getExtractedString(), Toast.LENGTH_SHORT).show();
	    	 if(subset.getExtractedString().equalsIgnoreCase("SUCCESS"))
	    	 {
	    		 
	    		 MusikLegal.on = true;
	    		 Editor e = mPreferences.edit();
	    		 e.remove("SubId");
	    		 e.remove("SubDate");
	    		 e.remove("SubDate");
	    		 e.commit();
		    	 e.putString("SubId", subset.getSiD());
		    	 e.putString("SubDate", subset.getDate());
		    	 e.putString("START", subset.getStart());
		    	 e.commit();
		    	 //Toast.makeText(getApplicationContext(), ((p?"true":"false")+" "+subset.getSiD()+ " "+ subset.getDate()+" "+subset.getStart()), Toast.LENGTH_SHORT).show();
	    	 }
	    	 else 
	    	 {
	    		 MusikLegal.on =false;
	    	 }
    	
    }
    
    void tryLogin()
    {
    	 
    	
    	final EditText etxt_pass = (EditText) findViewById(R.id.password);
		final EditText etxt_user = (EditText) findViewById(R.id.username);
		
		 new Thread(new Runnable(){

				public void run() {
					// TODO Auto-generated method stub
					String password = etxt_pass.getText().toString();
					String username = etxt_user.getText().toString();
					
					MainMenu.username=username;
					try {
						password = generatePass(password);
					} catch (NoSuchAlgorithmException e) {
						
						e.printStackTrace();
					}
			        DefaultHttpClient client = new DefaultHttpClient();
			        HttpPost login = new HttpPost("http://secure.musiklegal.com/user/validate");
			        HttpPost subs = new HttpPost("http://secure.musiklegal.com/subscription/check");
			        HttpPost info = new HttpPost("http://secure.musiklegal.com/user/user_info");
			        
			        
			        List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
			        List< BasicNameValuePair > nvss = new ArrayList< BasicNameValuePair >();
			        List< BasicNameValuePair > nvis = new ArrayList< BasicNameValuePair >();
			         
			        
			        nvps.add(new BasicNameValuePair("USERNAME", username));
			        nvps.add(new BasicNameValuePair("PASSWORD", password));
			        nvss.add(new BasicNameValuePair("USERNAME", username));
			        nvss.add(new BasicNameValuePair("UID", MusikLegal.getUID(getApplicationContext())));
			        nvis.add(new BasicNameValuePair("USERNAME", username));
			        nvis.add(new BasicNameValuePair("PASSWORD", password));
			        

			        try {

			        	  UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
			        	  UrlEncodedFormEntity s_entity = new UrlEncodedFormEntity(nvss,HTTP.UTF_8);
			        	  UrlEncodedFormEntity i_entity = new UrlEncodedFormEntity(nvis,HTTP.UTF_8);
			         	 
			        	  
			        	  login.setEntity(p_entity); 
			        	  subs.setEntity(s_entity);
			        	  info.setEntity(i_entity);
			        	  
			        	  
			              HttpResponse response = client.execute(login);
			               client = new DefaultHttpClient();
			              HttpResponse response2 = client.execute(info);
			               client = new DefaultHttpClient();
			              HttpResponse response3 = client.execute(subs);
			             
			            
			              HttpEntity responseEntity = response.getEntity();
			              HttpEntity responseEntity2 = response2.getEntity();
			              HttpEntity responseEntity3 = response3.getEntity();
			              
			              SAXParserFactory spf = SAXParserFactory.newInstance();
			              SAXParser sp = spf.newSAXParser();
			              XMLReader xr = sp.getXMLReader();
			              
			              SAXParserFactory bpf = SAXParserFactory.newInstance();
			              SAXParser bp = bpf.newSAXParser();
			              XMLReader br = bp.getXMLReader();

			              SAXParserFactory ipf = SAXParserFactory.newInstance();
			              SAXParser ip = ipf.newSAXParser();
			              XMLReader ir = ip.getXMLReader();
			              
			              LoginHandler loginHand = new LoginHandler();
			              LoginHandler subsHand = new LoginHandler();
			              LoginHandler infoHand = new LoginHandler();
			              
			              xr.setContentHandler(loginHand);
			              br.setContentHandler(subsHand);
			              ir.setContentHandler(infoHand);
			              
			              
			              xr.parse(retrieveInputStream(responseEntity));
			              ir.parse(retrieveInputStream(responseEntity2)); 
			              br.parse(retrieveInputStream(responseEntity3));
			             
			              ParsedLoginDataSet loginset = loginHand.getParsedLoginData();
			              ParsedLoginDataSet subset = subsHand.getParsedLoginData();
			              ParsedLoginDataSet inset = infoHand.getParsedLoginData();
			              
			              
			              if (loginset.getExtractedString().equals("SUCCESS")) 
			              {
			            	   
			                    SharedPreferences.Editor editor=mPreferences.edit();
			                    editor.putString("UserName", username);
			                    editor.putString("PassWord", password);
			                    editor.putString("FullName", inset.getFullName());
			                    editor.putString("Balance", inset.getBal());
			                    
			                    editor.putString("picture", inset.getProfPict());
			                    if(inset.getFB()!=null)
			                    {
			                    	if(inset.getFB().equals("0"))
			                    	{
			                    	editor.putString("FBId", username);
			                    	}
			                    	else
			                    	editor.putString("FBId", inset.getFB());
			                    }
			                    if(inset.getTW()!=null)
			                    {
			                    	if(inset.getTW().equals("0"))
			                    	{
			                    	editor.putString("TWId", username);
			                    	}
			                    	else
			                    	editor.putString("TWId", inset.getTW());
			                    }
			                    
			                    if(subset.getSiD()!=null)
			                    {
			                    	editor.putString("SubId", subset.getSiD());
			                    	on = true;
			                    }
			                    if(subset.getDate()!=null)
			                    {
			                    	editor.putString("SubDate", subset.getDate());
			                    }
			                    if(subset.getStart()!=null)
			                    {
			                    	editor.putString("START", subset.getStart());
			                    }
			                    
			                    editor.commit();
			                    
			                    try {
									appContact(getApplicationContext());
									//checkSubscription();
								} catch (ClientProtocolException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (ParserConfigurationException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (SAXException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
			                    
								 h.post(new Runnable(){

										public void run() {
			                    removeDialog(0);
			                    
			                    startActivity(new Intent(getApplicationContext(), MainMenu.class));
			                    MusikLegal.db = new DataHelper(MusikLegal.this);
			                    finish();
										}
									});
			                    
			                    
			              }
			              else {  
			            	 
			            	 
									// TODO Auto-generated method stub
			            	  h.post(new Runnable(){

									public void run() {
									 removeDialog(0);
									/*AlertDialog alertDialog3 = new AlertDialog.Builder(getApplicationContext()).create();
					      			alertDialog3.setTitle("Error Login");
					      			alertDialog3.setMessage("Invalid username or password");
					      			alertDialog3.setButton("OK", new DialogInterface.OnClickListener() { 
					      				public void onClick(DialogInterface dialog, int which) {
					      				//removeDialog(1);
					      				}
					      			});
					      			alertDialog3.setIcon(R.drawable.oc2);
					      			alertDialog3.show();*/
									 Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
								}});
			            	
			      			
			              }
			        } catch (final Exception e)
			        {
			        	//Looper.prepare();
			        	//h.post(new Runnable(){

							//public void run() {
								//removeDialog(1);
								//Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
								Log.e("exception", e.getMessage());
							//}});
			        	
			            
			        }
					
				}}).start();
		
  }
    static InputSource retrieveInputStream(HttpEntity httpEntity) {
        InputSource insrc = null;
        try {
              insrc = new InputSource(httpEntity.getContent());
        } catch (Exception e) {
        }
        return insrc;
  } 
  
    public String generatePass(String pass) throws NoSuchAlgorithmException
    {
    	MessageDigest m = MessageDigest.getInstance("MD5");
		byte[] data = pass.getBytes(); 
		m.update(data,0,data.length);
		BigInteger i = new BigInteger(1,m.digest());
		String str = String.format("%1$032X", i);
		return str.toLowerCase();
    }
    
    
    public static boolean internet(Context a) {
    	 NetworkInfo ni =((ConnectivityManager)a.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    	 return (ni==null)? false : ni.isConnected();
	}
    
   void forpass()
   {
	   AlertDialog.Builder alert = new AlertDialog.Builder(this);

	   alert.setTitle("Forgot Password");
	   alert.setMessage("Enter your email address");
 
	   final EditText input = new EditText(this);
	   alert.setView(input);

	   alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	   public void onClick(DialogInterface dialog, int whichButton) {
	     
		   	String email = input.getText().toString();
		   	DefaultHttpClient client = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost("http://secure.musiklegal.com/user/forgot_password");
	        List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
	        nvps.add(new BasicNameValuePair("EMAIL", email));
	 
	        try {   
	      	  	UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
	            
	            httppost.setEntity(p_entity);
	            
	            HttpResponse response = client.execute(httppost);
	            HttpEntity responseEntity = response.getEntity();
	            

	            SAXParserFactory spf = SAXParserFactory.newInstance();
	            SAXParser sp = spf.newSAXParser();
	            XMLReader xr = sp.getXMLReader();
	            
	            LoginHandler myLoginHandler = new LoginHandler();
	            xr.setContentHandler(myLoginHandler);
	            xr.parse(retrieveInputStream(responseEntity));
	            ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData();
	           
	            
	            if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) 
	            {
	            	Toast.makeText(getApplicationContext(), "Success, Check your email address to change password", Toast.LENGTH_SHORT).show();
	            	
	            } else  
	            {
	            	Toast.makeText(getApplicationContext(), "Invalid email address", Toast.LENGTH_SHORT).show();
	            }
	      } catch (Exception e)
	      {
	          
	      }
	     }
	   });

	   alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	     public void onClick(DialogInterface dialog, int whichButton) {
	      
	     }
	   });
	   alert.setIcon(R.drawable.oc2);
	   alert.show();  
   }
   
   public static String getUID(Context c)
   {
	   TelephonyManager telephonyManager = (TelephonyManager)c.getSystemService(Context.TELEPHONY_SERVICE);
       String UID=telephonyManager.getDeviceId();
       return "AD-"+UID;
   }
   
   public static void appContact(Context c) throws ClientProtocolException, IOException, ParserConfigurationException, SAXException
   {
	   String name =mPreferences.getString("UserName", null);
	   String uid = getUID(c);
	   
	   DefaultHttpClient client = new DefaultHttpClient();
	   
	   HttpPost subs = new HttpPost("http://secure.musiklegal.com/app_contact/contact");
	   List< BasicNameValuePair > nvss = new ArrayList< BasicNameValuePair >();
	   nvss.add(new BasicNameValuePair("USERNAME", name));
	   nvss.add(new BasicNameValuePair("UID",uid));
	   UrlEncodedFormEntity s_entity = new UrlEncodedFormEntity(nvss,HTTP.UTF_8);
   	 
   	//Toast.makeText(this, s_entity.toString(), Toast.LENGTH_LONG).show();
   	 
		 subs.setEntity(s_entity);
		 HttpResponse response3 = client.execute(subs);
		 HttpEntity responseEntity3 = response3.getEntity();
		 SAXParserFactory bpf = SAXParserFactory.newInstance();
		    SAXParser bp = bpf.newSAXParser();
		  XMLReader br = bp.getXMLReader();
		 LoginHandler subsHand = new LoginHandler();
		 br.setContentHandler(subsHand);
		 br.parse(retrieveInputStream(responseEntity3));
		 ParsedLoginDataSet subset = subsHand.getParsedLoginData();
		 if(subset.getExtractedString().equals("SUCCESS"))
		 {
			 
			 String current_date = subset.getCurrDate();
			 Log.d("app contact", "appcontact success ");
			 if(current_date!=null)
			 {
				 MusikLegal.current_date = current_date;
			 }
		 }
	   
   }
   
   
   
  }

